<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品管理系统 - 新增药品</title>
    <!-- 引入 Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- 引入 Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <style>
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
        }
        .required-label::after {
            content: " *";
            color: #dc3545;
        }
        .error-message {
            font-size: 0.875rem;
            color: #dc3545;
        }
        .table-hover tbody tr:hover {
            background-color: rgba(0, 0, 0, 0.075);
        }
        .action-buttons .btn {
            margin-right: 0.25rem;
        }
    </style>
</head>
<body>
<div class="container-fluid py-4">
    <!-- 页面标题 -->
    <div class="row mb-4">
        <div class="col">
            <h1 class="h3 mb-0">
                <i class="bi bi-capsule me-2"></i>药品管理系统
            </h1>
        </div>
    </div>

    <div class="row">
        <!-- 左侧表单 -->
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-plus-circle me-2"></i>新增/编辑药品
                    </h5>
                </div>
                <div class="card-body">
                    <form id="medicineForm">
                        <input type="hidden" id="medicineId">

                        <div class="mb-3">
                            <label for="name" class="form-label required-label">药品名称</label>
                            <input type="text" class="form-control" id="name" name="name" required>
                            <div class="error-message" id="nameError"></div>
                        </div>

                        <div class="mb-3">
                            <label for="specification" class="form-label required-label">药品规格</label>
                            <input type="text" class="form-control" id="specification" name="specification" required>
                            <div class="error-message" id="specificationError"></div>
                        </div>

                        <div class="mb-3">
                            <label for="price" class="form-label required-label">药品价格</label>
                            <div class="input-group">
                                <span class="input-group-text">¥</span>
                                <input type="number" class="form-control" id="price" name="price" min="0" step="0.01" required>
                            </div>
                            <div class="error-message" id="priceError"></div>
                        </div>

                        <div class="mb-3">
                            <label for="manufacturer" class="form-label">生产厂家</label>
                            <input type="text" class="form-control" id="manufacturer" name="manufacturer">
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">药品描述</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>

                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <button type="button" class="btn btn-secondary me-md-2" onclick="resetForm()">
                                <i class="bi bi-arrow-clockwise me-1"></i>重置
                            </button>
                            <button type="button" class="btn btn-success" onclick="saveMedicine()">
                                <i class="bi bi-check-lg me-1"></i>保存药品
                            </button>
                            <button type="button" class="btn btn-primary" id="updateBtn" style="display: none;" onclick="updateMedicine()">
                                <i class="bi bi-pencil me-1"></i>更新药品
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- 右侧药品列表 -->
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-list-ul me-2"></i>药品列表
                    </h5>
                    <button type="button" class="btn btn-light btn-sm" onclick="loadMedicineList()">
                        <i class="bi bi-arrow-repeat me-1"></i>刷新
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th>药品名称</th>
                                <th>规格</th>
                                <th>价格</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="medicineTableBody">
                            <!-- 药品列表将在这里动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入 Bootstrap JS 和 Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        loadMedicineList();
    });

    // 加载药品列表
    function loadMedicineList() {
        fetch('/medicine/list')
            .then(response => response.json())
            .then(data => {
                const tableBody = document.getElementById('medicineTableBody');

                if (data.code === 200 && data.data) {
                    tableBody.innerHTML = data.data.map(medicine => `
                            <tr>
                                <td>${medicine.name || ''}</td>
                                <td>${medicine.specification || ''}</td>
                                <td>¥${medicine.price ? medicine.price.toFixed(2) : '0.00'}</td>
                                <td class="action-buttons">
                                    <button class="btn btn-sm btn-outline-primary" onclick="editMedicine(${medicine.id})">
                                        <i class="bi bi-pencil"></i> 编辑
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteMedicine(${medicine.id})">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                } else {
                    tableBody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">暂无药品数据</td></tr>';
                }
            })
            .catch(error => {
                console.error('加载药品列表失败:', error);
                alert('加载药品列表失败');
            });
    }

    // 保存药品
    function saveMedicine() {
        if (!validateForm()) {
            return;
        }

        const medicine = {
            name: document.getElementById('name').value.trim(),
            specification: document.getElementById('specification').value.trim(),
            price: parseFloat(document.getElementById('price').value),
            manufacturer: document.getElementById('manufacturer').value.trim(),
            description: document.getElementById('description').value.trim()
        };

        fetch('/medicine/save', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(medicine)
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    alert(data.msg || '药品新增成功');
                    resetForm();
                    loadMedicineList();
                } else {
                    alert(data.msg || '药品新增失败');
                }
            })
            .catch(error => {
                console.error('保存药品失败:', error);
                alert('网络异常，请稍后重试');
            });
    }

    // 更新药品
    function updateMedicine() {
        if (!validateForm()) {
            return;
        }

        const medicine = {
            id: parseInt(document.getElementById('medicineId').value),
            name: document.getElementById('name').value.trim(),
            specification: document.getElementById('specification').value.trim(),
            price: parseFloat(document.getElementById('price').value),
            manufacturer: document.getElementById('manufacturer').value.trim(),
            description: document.getElementById('description').value.trim()
        };

        fetch('/medicine/update', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(medicine)
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    alert(data.msg || '药品更新成功');
                    resetForm();
                    loadMedicineList();
                } else {
                    alert(data.msg || '药品更新失败');
                }
            })
            .catch(error => {
                console.error('更新药品失败:', error);
                alert('网络异常，请稍后重试');
            });
    }

    // 编辑药品
    function editMedicine(id) {
        fetch(`/medicine/${id}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    const medicine = data.data;

                    // 填充表单
                    document.getElementById('medicineId').value = medicine.id;
                    document.getElementById('name').value = medicine.name || '';
                    document.getElementById('specification').value = medicine.specification || '';
                    document.getElementById('price').value = medicine.price || '';
                    document.getElementById('manufacturer').value = medicine.manufacturer || '';
                    document.getElementById('description').value = medicine.description || '';

                    // 切换按钮显示
                    document.querySelector('button[onclick="saveMedicine()"]').style.display = 'none';
                    document.getElementById('updateBtn').style.display = 'block';

                    // 滚动到表单顶部
                    document.querySelector('.card').scrollIntoView({ behavior: 'smooth' });
                } else {
                    alert('获取药品信息失败');
                }
            })
            .catch(error => {
                console.error('获取药品信息失败:', error);
                alert('获取药品信息失败');
            });
    }

    // 删除药品
    function deleteMedicine(id) {
        if (confirm('确定要删除这个药品吗？此操作不可恢复！')) {
            fetch(`/medicine/delete/${id}`, {
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert(data.msg || '药品删除成功');
                        loadMedicineList();
                    } else {
                        alert(data.msg || '药品删除失败');
                    }
                })
                .catch(error => {
                    console.error('删除药品失败:', error);
                    alert('删除失败，请稍后重试');
                });
        }
    }

    // 表单验证
    function validateForm() {
        let isValid = true;

        // 清除之前的错误信息
        document.querySelectorAll('.error-message').forEach(el => {
            el.textContent = '';
        });

        // 验证药品名称
        const name = document.getElementById('name').value.trim();
        if (!name) {
            document.getElementById('nameError').textContent = '请输入药品名称';
            isValid = false;
        }

        // 验证药品规格
        const specification = document.getElementById('specification').value.trim();
        if (!specification) {
            document.getElementById('specificationError').textContent = '请输入药品规格';
            isValid = false;
        }

        // 验证药品价格
        const price = document.getElementById('price').value;
        if (!price || isNaN(price) || parseFloat(price) < 0) {
            document.getElementById('priceError').textContent = '请输入有效的药品价格';
            isValid = false;
        }

        return isValid;
    }

    // 重置表单
    function resetForm() {
        document.getElementById('medicineForm').reset();
        document.getElementById('medicineId').value = '';

        // 清除错误信息
        document.querySelectorAll('.error-message').forEach(el => {
            el.textContent = '';
        });

        // 切换按钮显示
        document.querySelector('button[onclick="saveMedicine()"]').style.display = 'block';
        document.getElementById('updateBtn').style.display = 'none';
    }
</script>
</body>
</html>